<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, reactive, watch } from 'vue'
import * as echarts from 'echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { MapChart, ScatterChart, LinesChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GeoComponent,
  TimelineComponent,
  GridComponent,
} from 'echarts/components'

// 注册必要的组件
use([
  CanvasRenderer,
  MapChart,
  ScatterChart,
  LinesChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GeoComponent,
  TimelineComponent,
  GridComponent,
])

const props = defineProps({
  geoJson: {
    type: Object,
    required: true,
  },
  deData: {
    type: Object,
    required: true,
  },
})

const chartRef = ref(null)
let chart = null

// 地图坐标数据
const geoCoordMap = {
  黑龙江: [127.9688, 45.368],
  北京: [116.4551, 40.2539],
  辽宁: [123.1238, 42.1216],
  天津: [117.4219, 39.4189],
  山西: [112.3352, 37.9413],
  陕西: [109.1162, 34.2004],
  四川: [103.9526, 30.7617],
  重庆: [108.384366, 30.439702],
  山东: [117.1582, 36.8701],
  河南: [113.4668, 34.6234],
  江苏: [118.8062, 31.9208],
  安徽: [117.29, 32.0581],
  湖北: [114.3896, 30.6628],
  浙江: [119.5313, 29.8773],
  福建: [119.4543, 25.9222],
  江西: [116.0046, 28.6633],
  湖南: [113.0823, 28.2568],
  广东: [113.12244, 23.009505],
  海南: [110.3893, 19.8516],
  上海: [121.4648, 31.2891],
}

// 数据转换函数
const convertData = (data) => {
  const res = []
  for (let i = 0; i < data.length; i++) {
    const geoCoord = geoCoordMap[data[i].name]
    if (geoCoord) {
      res.push({
        name: data[i].name,
        value: geoCoord.concat(data[i].value),
      })
    }
  }
  return res
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  // 注册地图
  echarts.registerMap('china', props.geoJson)

  // 初始化图表实例
  chart = echarts.init(chartRef.value)

  // 生成数据
  debugger

  const mapData = []
  const categoryData = []
  const barData = []
  let maxValue = 0
  // 生成随机数据
  for (let i = 0; i < props?.deData?.mapData.length; i++) {
    categoryData.push(props?.deData?.mapData[i].province)
    if (props?.deData?.mapData[i].value > maxValue) {
      maxValue = props?.deData?.mapData[i].value
    }
    mapData.push({
      name: props?.deData?.mapData[i].province,
      value: props?.deData?.mapData[i].value,
    })
  }

  // mapData.push({
  //   year: 1111,
  //   name: '222',
  //   value: randomNum(100, 300),
  // })
  // // 处理柱状图数据
  // for (let i = 0; i < mapData.length; i++) {
  //   barData.push([])
  //   for (let j = 0; j < mapData[i].length; j++) {
  //     barData[i].push(mapData[i][j].value)
  //   }
  // }
  for (let j = 0; j < mapData.length; j++) {
    barData.push(mapData[j].value)
  }
  // 配置项
  const option = {
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicInOut',
    animationDurationUpdate: 1000,
    animationEasingUpdate: 'cubicInOut',
    grid: {
      right: '1%',
      top: '10%',
      bottom: '15%',
      width: '15%',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba(150,150,150,0.1)',
        },
      },
      valueFormatter: (value) => value + (props?.deData.type == 0 ? ' 万元' : '个'),
    },
    geo: {
      show: true,
      map: 'china',
      roam: true,
      zoom: 1,
      left: '13%',
      center: [113.83531246, 34.0267395887],
      label: {
        emphasis: {
          show: false,
        },
      },
      itemStyle: {
        normal: {
          borderColor: 'rgba(147, 235, 248, 1)',
          borderWidth: 1,
          areaColor: {
            type: 'radial',
            x: 0.5,
            y: 0.5,
            r: 0.8,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(147, 235, 248, 0)',
              },
              {
                offset: 1,
                color: 'rgba(147, 235, 248, .2)',
              },
            ],
            globalCoord: false,
          },
          shadowColor: 'rgba(128, 217, 248, 1)',
          shadowOffsetX: -2,
          shadowOffsetY: 2,
          shadowBlur: 10,
        },
        emphasis: {
          areaColor: '#389BB7',
          borderWidth: 0,
        },
      },
    },

    xAxis: {
      type: 'value',
      scale: true,
      position: 'top',
      min: 0,
      boundaryGap: false,
      splitLine: {
        show: false,
      },
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        margin: 2,
        textStyle: {
          color: '#aaa',
        },
      },
    },
    yAxis: {
      type: 'category',
      nameGap: 16,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#ddd',
        },
      },
      axisTick: {
        show: false,
        lineStyle: {
          color: '#ddd',
        },
      },
      axisLabel: {
        interval: 0,
        textStyle: {
          color: '#ddd',
        },
      },
      data: categoryData,
    },
    series: [
      {
        name: 'light',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: convertData(mapData),
        symbolSize: (val) => (val[2] / maxValue) * 20,
        label: {
          normal: {
            formatter: '{b}',
            position: 'right',
            show: true,
          },
          emphasis: {
            show: true,
          },
        },
        itemStyle: {
          normal: {
            color: '#1DE9B6',
          },
        },
      },
      {
        type: 'map',
        map: 'china',
        geoIndex: 0,
        aspectScale: 0.75,
        showLegendSymbol: false,
        label: {
          normal: {
            show: false,
          },
          emphasis: {
            show: false,
            textStyle: {
              color: '#fff',
            },
          },
        },
        roam: true,
        itemStyle: {
          normal: {
            areaColor: '#031525',
            borderColor: '#FFFFFF',
          },
          emphasis: {
            areaColor: '#2B91B7',
          },
        },
        animation: false,
        data: mapData,
      },
      {
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: convertData(mapData.sort((a, b) => b.value - a.value).slice(0, 20)),
        symbolSize: (val) => (val[2] / maxValue) * 30,
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
        },
        hoverAnimation: true,
        label: {
          normal: {
            formatter: '{b}',
            position: 'right',
            show: true,
          },
        },
        itemStyle: {
          normal: {
            color: '#1DE9B6',
            shadowBlur: 10,
            shadowColor: '#1DE9B6',
          },
        },
        zlevel: 1,
      },

      {
        zlevel: 1.5,
        type: 'bar',
        tooltip: {
          valueFormatter: (value) => value + (props?.deData.type == 0 ? ' 万元' : '个'),
        },
        itemStyle: {
          normal: {
            color: '#1DE9B6',
            barBorderRadius: 20,
          },
        },
        data: barData,
      },
    ],
  }

  // 设置配置项
  chart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  chart && chart.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})

watch(
  props,
  (newProps, oldProps) => {
    debugger
    initChart()
    console.log('props 变化了:', newProps)
  },
  { deep: true, immediate: true },
)
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
}
</style>
